using System.Collections.Generic;
using Unity.Entities;
using Unity.Mathematics;
using UnityEngine;

namespace DOTS.DOD.LESSON6
{
    [InternalBufferCapacity(8)]
    struct WayPoint : IBufferElementData
    {
        public float3 Point;
    }

    public class WayPointAuthoring : MonoBehaviour
    {
        public List<Vector3> WayPoints;

        class Baker : Baker<WayPointAuthoring>
        {
            public override void Bake(WayPointAuthoring authoring)
            {
                var entity = GetEntity(TransformUsageFlags.None);
                DynamicBuffer<WayPoint> wayPoints = AddBuffer<WayPoint>(entity);
                wayPoints.Length = authoring.WayPoints.Count;
                for (int i = 0; i < authoring.WayPoints.Count; i++)
                {
                    wayPoints[i] = new WayPoint()
                    {
                        Point = new float3(authoring.WayPoints[i]),
                    };
                }
            }
        }

        void Update()
        {
            if (Input.GetMouseButtonDown(0))
            {
                Vector3 worldPos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
                float3 wayPoint = new float3(worldPos.x, worldPos.y, 0);
                if (WayPoints.Count > 0)
                {
                    float minDis = float.MaxValue;
                    int index = 0;
                    for (int i = 0; i < WayPoints.Count; i++)
                    {
                        float dis = math.distance(wayPoint, WayPoints[i]);
                        if (dis < minDis)
                        {
                            minDis = dis;
                            index = i;
                        }
                    }

                    WayPoints.Insert(index, new Vector3(wayPoint.x, wayPoint.y, wayPoint.z));
                }
            }
        }

        void OnDrawGizmos()
        {
            if (WayPoints.Count >= 2)
            {
                Vector3 offset = new Vector3(0, 0, -1);
                for (int i = 0; i < WayPoints.Count; i++)
                {
                    Gizmos.color = Color.white;
                    Gizmos.DrawLine(WayPoints[i] + offset, WayPoints[(i + 1) % WayPoints.Count] + offset);
                    Gizmos.color = Color.cyan;
                    Gizmos.DrawSphere(WayPoints[i] + offset, 0.4f);
                }
            }
        }
    }
}